from flask import Flask, request, jsonify, send_from_directory
from flask_cors import CORS, cross_origin
import os
from sparkai.llm.llm import ChatSparkLLM, ChunkPrintHandler
from sparkai.core.messages import ChatMessage

app = Flask(__name__,static_folder='./')

@app.route('/api/chat', methods=['POST'])
@cross_origin()
def chat():
    data = request.get_json()  # 获取POST请求的JSON数据
    message = data.get('message', 'Hello')  # 从数据中提取消息，默认为'Hello'
    greeting = f'You said: {message}!'  # 构造问候语

    # 获取请求来源的 IP 地址
    remote_addr = request.headers.get('X-Forwarded-For', request.remote_addr)

    # 将消息和 IP 地址写入文件
    with open('../chat_log.txt', 'a') as file:
        file.write(f"IP: {remote_addr}, Message: {message}\n")

    return jsonify({'greeting': greeting})  # 返回JSON响应

@app.route('/api/chat_log', methods=['GET'])
@cross_origin()
def chat_log():
    try:
        # 读取聊天记录文件的最后50行
        with open('../chat_log.txt', 'r') as file:
            lines = file.readlines()
            # 如果聊天记录不足50行，则返回所有记录
            last_50_lines = lines[-50:] if len(lines) >= 50 else lines
        # 返回聊天记录的列表
        return jsonify(last_50_lines)
    except FileNotFoundError:
        # 如果文件不存在，返回空列表
        return jsonify([])
@app.route('/api/askAi',methods=['POST'])
@cross_origin()
def cahtwithAi():
    data = request.get_json()  # 获取POST请求的JSON数据
    print(data)
    # 星火认知大模型Spark Max的URL值，其他版本大模型URL值请前往文档（https://www.xfyun.cn/doc/spark/Web.html）查看
    SPARKAI_URL = 'wss://spark-api.xf-yun.com/v3.5/chat'
    # 星火认知大模型调用秘钥信息，请前往讯飞开放平台控制台（https://console.xfyun.cn/services/bm35）查看
    SPARKAI_APP_ID = 'd16f688b'
    SPARKAI_API_SECRET = 'M2Q2ZDM3MGY4YzZmYzgyM2NiNDdmNjAx'
    SPARKAI_API_KEY = 'f5871f26e082699875dcdc77ce2cb0f9'
    # 星火认知大模型Spark Max的domain值，其他版本大模型domain值请前往文档（https://www.xfyun.cn/doc/spark/Web.html）查看
    SPARKAI_DOMAIN = 'generalv3.5'
    spark = ChatSparkLLM(
            spark_api_url=SPARKAI_URL,
            spark_app_id=SPARKAI_APP_ID,
            spark_api_key=SPARKAI_API_KEY,
            spark_api_secret=SPARKAI_API_SECRET,
            spark_llm_domain=SPARKAI_DOMAIN,
            streaming=False,
    )
    messages = [ChatMessage(
        role="user",
        content=data['message']+"，请用简短的120字回复我"
    )]
    handler = ChunkPrintHandler()
    a = spark.generate([messages], callbacks=[handler])
    data2 = a.generations[0][0].text
    return jsonify(data2)
@app.route('/',methods=['GET'])
def gethtml():
    return send_from_directory(app.static_folder, './chat.html')

@app.route('/getAichat',methods=['GET'])
def getAichat():
    return send_from_directory(app.static_folder, './aichat.html')

if __name__ == '__main__':
    app.run(debug=True, host='0.0.0.0',threaded=True)  # 运行应用，并开启调试模式